import sys
import subprocess
import argparse
from pathlib import Path

def check_dependencies():
    """检查依赖"""
    print("🔍 检查依赖...")
    print(f"💡 当前Python环境路径: {sys.executable}")
    print(f"📦 已安装包列表:")
    result = subprocess.run([sys.executable, "-m", "pip", "list"], capture_output=True, text=True)
    print(result.stdout)

    # 检查Python版本
    if sys.version_info < (3, 8):
        print("❌ 需要Python 3.8+")
        return False

    # 检查MySQL
    try:
        import pymysql
        print("✅ PyMySQL已安装")
    except ImportError:
        print("❌ 未安装PyMySQL")
        print(f"🔄 正在安装PyMySQL...")
        try:
            subprocess.run([sys.executable, "-m", "pip", "install", "pymysql"], check=True)
            print("✅ PyMySQL安装完成")
        except subprocess.CalledProcessError as e:
            print(f"❌ PyMySQL安装失败: {e}")
            return False

    # 检查Redis
    try:
        import redis
        print("✅ Redis已安装")
    except ImportError:
        print("❌ 未安装Redis")
        print(f"🔄 正在安装Redis...")
        try:
            subprocess.run([sys.executable, "-m", "pip", "install", "redis"], check=True)
            print("✅ Redis安装完成")
        except subprocess.CalledProcessError as e:
            print(f"❌ Redis安装失败: {e}")
            return False

    return True


def setup_environment():
    """设置环境"""
    print("⚙️  设置环境...")

    # 创建.env文件
    env_file = Path(".env")
    if not env_file.exists():
        print("📄 创建.env文件...")
        try:
            with open(".env", "r") as src:
                with open(".env", "w") as dst:
                    dst.write(src.read())
            print("✅ .env文件创建成功")
        except Exception as e:
            print(f"❌ .env文件创建失败: {e}")
            return False
    else:
        print("✅ .env文件已存在")

    # 创建日志目录
    log_dir = Path("logs")
    try:
        log_dir.mkdir(exist_ok=True)
        print(f"✅ 日志目录 '{log_dir.absolute()}' 创建成功")
    except Exception as e:
        print(f"❌ 日志目录创建失败: {e}")
        return False

    print("✅ 环境设置完成")
    return True


def install_dependencies():
    """安装依赖"""
    print("📦 安装依赖...")
    try:
        # 添加--no-cache-dir避免缓存问题，-q让输出更简洁
        result = subprocess.run(
            [sys.executable, "-m", "pip", "install", "--no-cache-dir", "-q", "-r", "requirements.txt"],
            check=True, 
            capture_output=True
        )
        print("✅ 依赖安装完成")
    except subprocess.CalledProcessError as e:
        print(f"❌ 依赖安装失败: {e}")
        print(f"错误输出: {e.stderr.decode()}")
        return False
    return True


def init_database():
    """初始化数据库"""
    print("🗄️  初始化数据库...")
    try:
        from app.core.config.database import engine, Base
        from app.models.database.models import Base as ModelsBase

        # 初始化所有模型
        Base.metadata.create_all(bind=engine)
        print("✅ 数据库初始化完成")
    except Exception as e:
        print(f"❌ 数据库初始化失败: {e}")
        return False
    return True


def start_services():
    """启动服务"""
    print("🚀 启动服务...")

    # 启动FastAPI
    print("🌐 启动FastAPI服务...")
    print("访问: http://localhost:8000/docs")
    print("API文档: http://localhost:8000/docs")

    # 启动Celery
    print("📋 启动Celery...")
    print("使用命令: celery -A app.core.celery worker --loglevel=info")

    return True


def main(args):
    """主函数"""
    print("🎯 灾备服务快速启动")
    print("=" * 50)

    # 根据参数选择执行哪些步骤
    if args.skip_deps and args.skip_setup and args.skip_install and args.skip_db:
        print("⚠️ 跳过所有初始化步骤，直接启动服务")
        if not start_services():
            print("❌ 服务启动失败")
            return

    if not args.skip_deps:
        if not check_dependencies():
            print("❌ 依赖检查失败")
            return

    if not args.skip_setup:
        if not setup_environment():
            print("❌ 环境设置失败")
            return

    if not args.skip_install:
        if not install_dependencies():
            print("❌ 依赖安装失败")
            return

    if not args.skip_db:
        if not init_database():
            print("❌ 数据库初始化失败")
            return

    if not args.no_start:
        if not start_services():
            print("❌ 服务启动失败")
            return

    print("🎉 灾备服务启动完成!")
    print("下一步: ")
    print("1. 访问 http://localhost:8000/docs 查看API文档")
    print("2. 使用POST /services 创建服务配置")
    print("3. 系统会自动开始监控服务状态")


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="灾备服务快速启动脚本")
    parser.add_argument("--skip-deps", action="store_true", dest="skip_deps", help="跳过依赖检查")
    parser.add_argument("--skip-setup", action="store_true", dest="skip_setup", help="跳过环境设置")
    parser.add_argument("--skip-install", action="store_true", dest="skip_install", help="跳过依赖安装")
    parser.add_argument("--skip-db", action="store_true", dest="skip_db", help="跳过数据库初始化")
    parser.add_argument("--no-start", action="store_true", dest="no_start", help="不自动启动服务")
    
    args = parser.parse_args()
    
    main(args)